<template>
  <div class="login-container">
    <van-nav-bar fixed left-arrow @click-left="$router.back()" title="校园超市">
      <template #right>
        <van-icon @click="$router.push('/')" name="shop-o" size="20" />
      </template>
    </van-nav-bar>

    <img src="@/assets/imgs/logo.jpg" class="logo">

    <van-form ref="loginForm" @submit="login">
      <van-field :maxlength="11"
        :rules="[{ required: true, message: '请输入手机号' }, { pattern: telPattern, message: '请输入合法的手机号' }]" v-model="phone"
        placeholder="请输入手机号" />
      <van-field :rules="[{ required: true, message: '请输入登录密码' }]" type="password" v-model="password"
        placeholder="请输入登录密码" />
      <van-button native-type="submit" block round type="primary">立即登录</van-button>
    </van-form>

    <router-link class="link" to="/register">
      没有账号,立即注册
    </router-link>
  </div>
</template>
  
<script>
import _ from 'lodash';
import useCartStore from '@/store/cartStore';
import { ref,inject } from 'vue';
export default {
  setup() {
    const axios=inject('axios');
    const router=inject('router');
    const route=inject('route').value;
    const showToast=inject('showToast');
    // 默认账号和密码
    const phone = ref('18710950999');
    const password = ref('123');
    const telPattern = /^1[3456789]\d{9}$/;
    const loginForm=ref();
    const {getCartList}=useCartStore();
    // 登录按钮点击事件处理函数: 防抖
    const  login= _.debounce(function () {
      showToast('提示内容');
      loginForm.value.validate().then(() => {
        axios.post('/login', { phone: phone.value, password: password.value }).then(res => {
          showToast(res.msg);
          if (res.code == 200) {
            localStorage.setItem('userLoginInfo', JSON.stringify(res.list));
            // 请求购物车列表数据
            getCartList();
            // 自动跳转到用户之前操作的页面 或者 会员中心
            let url = route.query.url ? route.query.url : '/ucenter';
            router.push(url);
          }
        });
      }).catch(() => {
        console.log('表单校验失败');
      })

    })
    return {
      phone,password,telPattern,loginForm,login
    }
  }
}
</script>
  
<style lang="scss">
.login-container {
  padding: 10px;

  .logo {
    width: 80px;
    height: 80px;
    display: block;
    margin: 40px auto;
  }

  h3 {
    font-size: 30px;
    color: #444;
    font-weight: normal;
    margin: 30px 0;
    text-align: center;

  }

  .van-cell {
    background: #f2f2f2;
    border-radius: 20px;
    margin: 20px 0;
  }

  .link {
    margin: 15px;
    font-size: 14px;
    display: block;
    color: #333;
    text-align: center;
  }
}
</style>